<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>电子相册系统</title>
<link rel="stylesheet" href="/css/style.css">
<!-- <link rel="stylesheet" href="style.css"> -->
</head>
<body>
<div class="page">
	<nav style="background:var(--card);border-radius:12px;padding:18px;box-shadow:var(--shadow);min-width:180px;display:flex;gap:18px;align-items:center;margin-bottom:24px;">
		<button class="btn ghost" id="navCategory" onclick="showSection('category')">类别管理</button>
		<button class="btn ghost" id="navAlbum" onclick="showSection('album')">相册管理</button>
		<button class="btn ghost" id="navUser" onclick="showSection('user')">用户管理</button>
	</nav>
	<div id="sectionCategory">
		<div class="admin-panel">
			<h2 class="title">类别管理</h2>
			<div id="category-list" class="cat-list"></div>
			<div style="margin-top:18px;">
				<input type="text" id="new-category" class="field" placeholder="新类别名称">
				<button class="btn" id="add-category">添加类别</button>
			</div>
		</div>
	</div>
	<div id="sectionAlbum" style="display:none;">
		<div class="admin-panel">
			<h2 class="title">相册管理</h2>
			<div id="album-list"></div>
		</div>
	</div>
	<div id="sectionUser" style="display:none;">
		<div class="admin-panel">
			<h2 class="title">用户管理</h2>
			<div id="user-list"></div>
		</div>
	</div>
</div>

<script>

	window.onload = function() {
		checkifAdmin();
	}
function showSection(section) {
	document.getElementById('sectionCategory').style.display = (section === 'category') ? '' : 'none';
	document.getElementById('sectionAlbum').style.display = (section === 'album') ? '' : 'none';
	document.getElementById('sectionUser').style.display = (section === 'user') ? '' : 'none';
	document.getElementById('navCategory').classList.toggle('active', section === 'category');
	document.getElementById('navAlbum').classList.toggle('active', section === 'album');
	document.getElementById('navUser').classList.toggle('active', section === 'user');
	if (section === 'category') {
		loadCategoriesAdmin();
	}
}


// 类别管理逻辑（复用Main页面思路）
function loadCategoriesAdmin() {
	fetch('/getcategorylist')
		.then(res => res.json())
		.then(categories => {
			const catDiv = document.getElementById('category-list');
			catDiv.innerHTML = '';
			categories.forEach(cat => {
				const pill = document.createElement('div');
				pill.className = 'cat-pill';
				pill.textContent = cat;
				// 删除按钮
				const delBtn = document.createElement('button');
				delBtn.className = 'admin-mini-btn';
				delBtn.textContent = '删除';
				delBtn.style.marginLeft = '8px';
				delBtn.onclick = function() {
					if (confirm('确定要删除该类别吗？')) {
						if( cat === '默认' ) {
							alert('默认类别不能删除！');
							return;
						}
						fetch('/deletecategory', {
							method: 'POST',
							headers: { 'Content-Type': 'application/json' },
							body: JSON.stringify({ categoryname: cat })
						})
						.then(res => res.json())
						.then(data => {
							if (data.success) {
								alert('删除成功！');
								loadCategoriesAdmin();
							} else {
								alert('删除失败：' + data.message);
							}
						});
					}
				};
				pill.appendChild(delBtn);
				catDiv.appendChild(pill);
			});
		});
}

// 相册管理逻辑（列表样式）
function loadAlbumsAdmin() {
	fetch('/getallalbumsbrief')
		.then(res => res.json())
		.then(albums => {
			const listDiv = document.getElementById('album-list');
			listDiv.innerHTML = '';
			// 表头
			const header = document.createElement('div');
			header.style = 'display:flex;font-weight:700;padding:8px 0;border-bottom:2px solid #e6eef8;gap:16px;';
			header.innerHTML = '<span style="width:60px;">ID</span><span style="flex:1;">标题</span><span style="width:120px;">作者</span><span style="width:100px;">类别</span>';
			listDiv.appendChild(header);
			// 每一行
			albums.forEach(album => {
				const row = document.createElement('div');
				row.style = 'display:flex;align-items:center;padding:8px 0;border-bottom:1px dashed #e6eef8;gap:16px;cursor:pointer;';
				row.onclick = () => window.location.href = `/albummanagement/${album.albumId}`;
				row.innerHTML = `
					<span style="width:60px;">${album.albumId}</span>
					<span style="flex:1;">${album.title}</span>
					<span style="width:120px;">${album.author}</span>
					<span style="width:100px;">${album.category}</span>
				`;
				listDiv.appendChild(row);
			});
		});
}


// 用户管理逻辑
function loadUsersAdmin() {
	fetch('/getalluserslist')
		.then(res => res.json())
		.then(data => {
			const users = data.users || [];
			const listDiv = document.getElementById('user-list');
			listDiv.innerHTML = '';
			// 表头
			const header = document.createElement('div');
			header.style = 'display:flex;font-weight:700;padding:8px 0;border-bottom:2px solid #e6eef8;gap:16px;';
			header.innerHTML = '<span style="width:60px;">ID</span><span style="flex:1;">用户名</span><span style="width:100px;">角色</span><span style="width:80px;">状态</span><span style="width:120px;">操作</span>';
			listDiv.appendChild(header);
			// 每一行
			users.forEach(user => {
				const row = document.createElement('div');
				row.style = 'display:flex;align-items:center;padding:8px 0;border-bottom:1px dashed #e6eef8;gap:16px;';
				row.innerHTML = `
					<span style="width:60px;">${user.userId}</span>
					<span style="flex:1;">${user.username}</span>
					<span style="width:100px;">${user.role}</span>
					<span style="width:80px;">${user.status == 1 ? '已封禁' : '正常'}</span>
				`;
				// 操作按钮
				const opDiv = document.createElement('span');
				opDiv.style = 'width:120px;display:flex;gap:8px;';
				if (user.status == 1) {
					// 已封禁，显示解封
					const unbanBtn = document.createElement('button');
					unbanBtn.className = 'admin-mini-btn';
					unbanBtn.textContent = '解封';
					unbanBtn.onclick = function() {
						if (confirm('确定要解封该用户吗？')) {
							fetch('/unbanuser', {
								method: 'POST',
								headers: { 'Content-Type': 'application/json' },
								body: JSON.stringify({ userId: user.userId })
							})
							.then(res => res.json())
							.then(data => {
								if (data.success) {
									alert('已解封');
									loadUsersAdmin();
								} else {
									alert('操作失败：' + data.message);
								}
							});
						}
					};
					opDiv.appendChild(unbanBtn);
				} else {
					// 正常，显示封禁
					const banBtn = document.createElement('button');
					banBtn.className = 'admin-mini-btn';
					banBtn.textContent = '封禁';
					banBtn.onclick = function() {
						if (confirm('确定要封禁该用户吗？')) {
							fetch('/banuser', {
								method: 'POST',
								headers: { 'Content-Type': 'application/json' },
								body: JSON.stringify({ userId: user.userId })
							})
							.then(res => res.json())
							.then(data => {
								if (data.success) {
									alert('已封禁');
									loadUsersAdmin();
								} else {
									alert('操作失败：' + data.message);
								}
							});
						}
					};
					opDiv.appendChild(banBtn);
				}
				row.appendChild(opDiv);
				listDiv.appendChild(row);
			});
		});
}

// 切换区块时加载相册/用户列表
const oldShowSection = showSection;
showSection = function(section) {
	document.getElementById('sectionCategory').style.display = (section === 'category') ? '' : 'none';
	document.getElementById('sectionAlbum').style.display = (section === 'album') ? '' : 'none';
	document.getElementById('sectionUser').style.display = (section === 'user') ? '' : 'none';
	document.getElementById('navCategory').classList.toggle('active', section === 'category');
	document.getElementById('navAlbum').classList.toggle('active', section === 'album');
	document.getElementById('navUser').classList.toggle('active', section === 'user');
	if (section === 'category') {
		loadCategoriesAdmin();
	}
	if (section === 'album') {
		loadAlbumsAdmin();
	}
	if (section === 'user') {
		loadUsersAdmin();
	}
}

document.getElementById('add-category').onclick = function() {
	const categoryName = document.getElementById('new-category').value.trim();
	if (!categoryName) return alert('请输入类别名称');
	fetch('/addcategory', {
		method: 'POST',
		headers: {
			'Content-Type': 'application/json'
		},
		body: JSON.stringify({ categoryname: categoryName })
	})
	.then(res => res.json())
	.then(data => {
		if (data.success) {
			alert('类别添加成功！');
			document.getElementById('new-category').value = '';
			loadCategoriesAdmin();
		} else {
			alert('类别添加失败：' + data.message);
		}
	});
};

function checkifAdmin() {
	fetch('/getuserinfo')
	.then(res => res.json())
	.then(data => {
		if (data.role !== '管理员') {
			alert('无权限访问此页面');
			window.location.href = '/main';
		}
	});
}
// 页面初始化时加载类别
showSection('category');
</script>
</body>
</html>
